﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using LOGISTCBUS.DAO;
using LOGISTCBUS.Entities;

namespace LOGISTCBUS.WebUI.Controllers
{
    [HandleError(View = "Error")]
    public class AccountController : Controller
    {
        public ActionResult LogOn()
        {
            string login = string.Empty;
            if (!String.IsNullOrEmpty(Request.Params["txtLogin"]))
                login = Request.Params["txtLogin"];
            string password = string.Empty;
            if (!String.IsNullOrEmpty(Request.Params["txtPassword"]))
                password = Encryption.EncryptMd5(Request.Params["txtPassword"]);

            if (!String.IsNullOrEmpty(login) && !String.IsNullOrEmpty(password))
            {
                var user = new UserDAO().doLogin(login, password);
                if (user != null)
                {
                    if (user.Id > 0)
                    {
                        Session["remote_addr"] = string.IsNullOrEmpty(Request.ServerVariables["REMOTE_ADDR"]) ? string.Empty : Request.ServerVariables["REMOTE_ADDR"];
                        Session["remote_host"] = string.IsNullOrEmpty(Request.ServerVariables["REMOTE_HOST"]) ? string.Empty : Request.ServerVariables["REMOTE_HOST"];

                        var loggedUser = string.Empty;
                        if (user.Name.IndexOf(" ") > 0)
                            loggedUser = user.Name.Substring(0, user.Name.IndexOf(" "));
                        else
                            loggedUser = user.Name.Substring(0, user.Name.Length);

                        this.Session["loggedUser"] = loggedUser.Trim();
                        this.Session["user"] = user;
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        this.ViewData["error"] = "Nome de usuário ou senha incorreta.";
                    }
                }
            }
            return View();
        }

        public ActionResult LogOut()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("LogOn", "Account");
        }
    }
}
